<template>
	<view class="container">
		<view v-if="loading" class="loading">
			<text>加载中...</text>
		</view>
		
		<view v-else-if="device" class="content">
			<!-- 设备基本信息 -->
			<view class="section">
				<view class="section-title">设备信息</view>
				<view class="info-card">
					<view class="info-row">
						<text class="label">设备名称</text>
						<text class="value">{{ device.deviceName }}</text>
					</view>
					<view class="info-row">
						<text class="label">设备编号</text>
						<text class="value">{{ device.deviceId }}</text>
					</view>
					<view class="info-row">
						<text class="label">设备类型</text>
						<text class="value">{{ device.deviceType }}</text>
					</view>
				</view>
			</view>

			<!-- 设备配置参数 -->
			<view class="section">
				<view class="section-title">配置参数</view>
				<view class="config-card">
					<view class="config-item">
						<text class="config-label">采样频率</text>
						<view class="config-value">
							<input 
								v-model="config.samplingRate" 
								class="config-input" 
								placeholder="请输入采样频率(秒)"
								type="number"
							/>
						</view>
					</view>
					<view class="config-item">
						<text class="config-label">数据上传间隔</text>
						<view class="config-value">
							<input 
								v-model="config.uploadInterval" 
								class="config-input" 
								placeholder="请输入上传间隔(分钟)"
								type="number"
							/>
						</view>
					</view>
					<view class="config-item">
						<text class="config-label">告警阈值</text>
						<view class="config-value">
							<input 
								v-model="config.alertThreshold" 
								class="config-input" 
								placeholder="请输入告警阈值"
								type="number"
							/>
						</view>
					</view>
					<view class="config-item">
						<text class="config-label">工作模式</text>
						<view class="config-value">
							<picker 
								:value="workModeIndex" 
								:range="workModes" 
								@change="onWorkModeChange"
								class="config-picker"
							>
								<view class="picker-text">{{ workModes[workModeIndex] }}</view>
							</picker>
						</view>
					</view>
					<view class="config-item">
						<text class="config-label">自动校准</text>
						<view class="config-value">
							<switch 
								:checked="config.autoCalibration" 
								@change="onAutoCalibrationChange"
								color="#2E7D32"
							/>
						</view>
					</view>
				</view>
			</view>

			<!-- 网络配置 -->
			<view class="section">
				<view class="section-title">网络配置</view>
				<view class="config-card">
					<view class="config-item">
						<text class="config-label">服务器地址</text>
						<view class="config-value">
							<input 
								v-model="config.serverUrl" 
								class="config-input" 
								placeholder="请输入服务器地址"
							/>
						</view>
					</view>
					<view class="config-item">
						<text class="config-label">端口号</text>
						<view class="config-value">
							<input 
								v-model="config.port" 
								class="config-input" 
								placeholder="请输入端口号"
								type="number"
							/>
						</view>
					</view>
					<view class="config-item">
						<text class="config-label">连接超时</text>
						<view class="config-value">
							<input 
								v-model="config.timeout" 
								class="config-input" 
								placeholder="请输入超时时间(秒)"
								type="number"
							/>
						</view>
					</view>
				</view>
			</view>

			<!-- 操作按钮 -->
			<view class="action-buttons">
				<button class="btn-primary" @click="saveConfig">保存配置</button>
				<button class="btn-secondary" @click="resetConfig">重置配置</button>
				<button class="btn-secondary" @click="testConnection">测试连接</button>
			</view>
		</view>

		<view v-else class="empty">
			<text>设备信息不存在</text>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { getDeviceDetail, updateDeviceConfig } from '@/api/device.js'

const loading = ref(false)
const device = ref(null)
const deviceId = ref('')

// 配置参数
const config = ref({
	samplingRate: 60,
	uploadInterval: 5,
	alertThreshold: 7.0,
	workMode: 'auto',
	autoCalibration: true,
	serverUrl: 'http://127.0.0.1:8891',
	port: 8891,
	timeout: 30
})

// 工作模式选项
const workModes = ['自动模式', '手动模式', '节能模式', '维护模式']
const workModeIndex = ref(0)

// 获取当前设备ID
const getCurrentDeviceId = () => {
	const pages = getCurrentPages()
	const currentPage = pages[pages.length - 1]
	const id = currentPage.options?.deviceId
	
	console.log('配置页面参数:', currentPage.options)
	console.log('设备ID:', id)
	
	return id
}

// 获取设备详情
const fetchDetail = async () => {
	try {
		loading.value = true
		deviceId.value = getCurrentDeviceId()
		
		if (!deviceId.value) {
			uni.showModal({
				title: '参数错误',
				content: '未获取到设备ID，请从设备列表重新进入',
				showCancel: false,
				success: () => {
					uni.navigateBack()
				}
			})
			return
		}
		
		const res = await getDeviceDetail(deviceId.value)
		console.log('设备详情响应:', res)
		
		if (res && res.code === 200) {
			device.value = res.obj
			// 加载设备配置
			loadDeviceConfig()
		} else {
			uni.showToast({
				title: res?.msg || '获取设备信息失败',
				icon: 'none'
			})
		}
	} catch (error) {
		console.error('获取设备详情失败:', error)
		uni.showToast({
			title: '获取设备信息失败',
			icon: 'none'
		})
	} finally {
		loading.value = false
	}
}

// 加载设备配置
const loadDeviceConfig = () => {
	// 这里应该从设备配置API获取配置信息
	// 暂时使用默认配置
	console.log('加载设备配置')
}

// 工作模式改变
const onWorkModeChange = (e) => {
	workModeIndex.value = e.detail.value
	config.value.workMode = workModes[e.detail.value]
}

// 自动校准开关改变
const onAutoCalibrationChange = (e) => {
	config.value.autoCalibration = e.detail.value
}

// 保存配置
const saveConfig = async () => {
	try {
		uni.showLoading({ title: '保存中...' })
		
		// 验证配置参数
		if (!config.value.samplingRate || config.value.samplingRate <= 0) {
			uni.showToast({
				title: '请输入有效的采样频率',
				icon: 'none'
			})
			return
		}
		
		if (!config.value.uploadInterval || config.value.uploadInterval <= 0) {
			uni.showToast({
				title: '请输入有效的上传间隔',
				icon: 'none'
			})
			return
		}
		
		// 调用保存配置API
		const res = await updateDeviceConfig(deviceId.value, config.value)
		console.log('保存配置响应:', res)
		
		if (res && res.code === 200) {
			uni.showToast({
				title: '配置保存成功',
				icon: 'success'
			})
		} else {
			uni.showToast({
				title: res?.msg || '保存配置失败',
				icon: 'none'
			})
		}
	} catch (error) {
		console.error('保存配置失败:', error)
		uni.showToast({
			title: '保存配置失败',
			icon: 'none'
		})
	} finally {
		uni.hideLoading()
	}
}

// 重置配置
const resetConfig = () => {
	uni.showModal({
		title: '确认重置',
		content: '确定要重置为默认配置吗？',
		success: (res) => {
			if (res.confirm) {
				config.value = {
					samplingRate: 60,
					uploadInterval: 5,
					alertThreshold: 7.0,
					workMode: 'auto',
					autoCalibration: true,
					serverUrl: 'http://127.0.0.1:8891',
					port: 8891,
					timeout: 30
				}
				workModeIndex.value = 0
				uni.showToast({
					title: '配置已重置',
					icon: 'success'
				})
			}
		}
	})
}

// 测试连接
const testConnection = async () => {
	try {
		uni.showLoading({ title: '测试连接中...' })
		
		// 这里应该调用测试连接的API
		// 暂时模拟测试结果
		await new Promise(resolve => setTimeout(resolve, 2000))
		
		uni.showToast({
			title: '连接测试成功',
			icon: 'success'
		})
	} catch (error) {
		console.error('连接测试失败:', error)
		uni.showToast({
			title: '连接测试失败',
			icon: 'none'
		})
	} finally {
		uni.hideLoading()
	}
}

// 页面显示时刷新数据
onShow(() => {
	console.log('配置页面显示，检查是否需要刷新')
	
	const deviceUpdated = uni.getStorageSync('device_updated')
	if (deviceUpdated) {
		uni.removeStorageSync('device_updated')
		fetchDetail()
	}
})

onMounted(() => {
	fetchDetail()
})
</script>

<style scoped>
.container {
	min-height: 100vh;
	background: #f8fffe;
	padding: 20rpx;
}

.loading {
	display: flex;
	justify-content: center;
	align-items: center;
	height: 400rpx;
	color: #666;
}

.content {
	padding-bottom: 100rpx;
}

.section {
	margin-bottom: 30rpx;
}

.section-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #2E7D32;
	margin-bottom: 20rpx;
	padding-left: 10rpx;
	border-left: 6rpx solid #2E7D32;
}

.info-card, .config-card {
	background: #ffffff;
	border-radius: 12rpx;
	padding: 30rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.info-row {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx 0;
	border-bottom: 1rpx solid #f0f0f0;
}

.info-row:last-child {
	border-bottom: none;
}

.label {
	font-size: 28rpx;
	color: #666;
	font-weight: 500;
}

.value {
	font-size: 28rpx;
	color: #333;
	font-weight: 600;
}

.config-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 25rpx 0;
	border-bottom: 1rpx solid #f0f0f0;
}

.config-item:last-child {
	border-bottom: none;
}

.config-label {
	font-size: 28rpx;
	color: #666;
	font-weight: 500;
	min-width: 200rpx;
}

.config-value {
	flex: 1;
	display: flex;
	justify-content: flex-end;
	align-items: center;
}

.config-input {
	flex: 1;
	text-align: right;
	font-size: 28rpx;
	color: #333;
	padding: 10rpx 15rpx;
	border: 1rpx solid #ddd;
	border-radius: 8rpx;
	background: #fafafa;
}

.config-picker {
	flex: 1;
	text-align: right;
}

.picker-text {
	font-size: 28rpx;
	color: #333;
	padding: 10rpx 15rpx;
	border: 1rpx solid #ddd;
	border-radius: 8rpx;
	background: #fafafa;
}

.action-buttons {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background: #ffffff;
	padding: 20rpx;
	border-top: 1rpx solid #e8f5e8;
	display: flex;
	gap: 20rpx;
}

.btn-primary {
	flex: 1;
	background: #2E7D32;
	color: #ffffff;
	border: none;
	border-radius: 8rpx;
	padding: 20rpx;
	font-size: 28rpx;
	font-weight: 600;
}

.btn-secondary {
	flex: 1;
	background: #ffffff;
	color: #2E7D32;
	border: 1rpx solid #2E7D32;
	border-radius: 8rpx;
	padding: 20rpx;
	font-size: 28rpx;
	font-weight: 600;
}

.empty {
	display: flex;
	justify-content: center;
	align-items: center;
	height: 400rpx;
	color: #999;
	font-size: 28rpx;
}
</style>
